/*
 * File:   main.cpp
 * Author: samcrow
 *
 * Created on March 4, 2012, 4:13 PM
 */

#include <iostream>

#include <libfreenect.hpp>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>

#include "serialUltrasonic.h"


using namespace std;

/*
 *
 */
int main(int argc, char** argv) {

    SerialUltrasonic ultrasonic("/dev/ttyUSB0", 9600);

    usleep(.2 * 1000 * 1000);
    cout << ultrasonic.getDistance() << endl;


	int port = 7510;

	int socketID = socket(AF_INET, SOCK_STREAM, 0);
	if(socketID < 0){
		cout << "Error initializing socket" << endl;
	}

	struct sockaddr_in serverAddress;
	//C: Initialize everything in the serverAddress to 0
	bzero((char *) &serverAddress, sizeof(serverAddress));
	serverAddress.sin_family = AF_INET;
	serverAddress.sin_port = htons(port);//htons() converts from the system byte order to the standard networking byte order
	serverAddress.sin_addr.s_addr = INADDR_ANY;//I don't know what this does

	//Bind to the port
	int bindValue = bind(socketID, (struct sockaddr *) &serverAddress, sizeof(serverAddress));
	if(bindValue < 0){
		cout << "Error binding socket to port " << port << endl;
	}

	listen(socketID, 5);//Start listening

	struct sockaddr_in cli_addr;//I don't know what this does
	socklen_t clilen = sizeof(cli_addr);//I don't know what this does
	bzero((char *) &cli_addr, clilen);


	cout << "About to block waiting for a connection..." << endl;
	int newSocket = accept(socketID, (struct sockaddr *) &cli_addr, &clilen);
	cout << "Got a connection." << endl;
	if(newSocket < 0){
		cout << "Socket accept error: " << newSocket << endl;
		cout << "errno: " << errno << endl;
	}
	cout << "New socket ID: " << newSocket << endl;


	while(true){
		std::string distance = ultrasonic.getDistanceString();

		cout << "About to write." << endl;
		distance += "\n";//Append \n to the end
		write(newSocket, distance.c_str(), distance.length());

		cout << distance << endl;


		usleep(.1 * 1000 * 1000);//Wait for 0.2 seconds
	}

	close(newSocket);
	close(socketID);

    return 0;
}